package main;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.InetAddress;

// @ Servidor
public class CodifMsjdelCAP {

	private String str_encoding_scheme = "UTF-8";
	
	// Convierte el string txt en una cadena de bytes utilizando 
	// el esquema "esquema" y lo pone en el dataoutput stream
	
	private void writeString(DataOutputStream out, String txt, String esquema){
		byte[] txt_en_bytes = null;
		try {
			txt_en_bytes = txt.getBytes(esquema);
			out.writeInt(txt_en_bytes.length);
			out.write(txt_en_bytes);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	private String readString(DataInputStream in) throws IOException{
		byte[] buf;
		int l = in.readInt();
		
		buf = new byte[l];
		in.readFully(buf);
		
		return new String(buf, str_encoding_scheme);
	}
	
	
	public byte[] alCable(Mensaje_del_CAP msj) throws IOException{
		ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
		DataOutputStream out = new DataOutputStream(byteStream);
		
		out.writeInt(msj.getID());  		// ID msj
		out.writeInt(msj.getIDorigen());	// ID chacra
		writeString(out, msj.getIPorigen().getHostAddress(), str_encoding_scheme); // IP origen
		writeString(out, msj.getCuerpo(), str_encoding_scheme);
		
		out.flush();
		out.close();
		
		return byteStream.toByteArray();
	}
	
	public Mensaje_del_CAP delCable(byte[] input) throws IOException{
		ByteArrayInputStream bs = new ByteArrayInputStream(input);
		DataInputStream in = new DataInputStream(bs);
		Mensaje_del_CAP msj = new Mensaje_del_CAP();
		
		msj.setID(in.readInt()); 			// ID msj
		msj.setIDorigen(in.readInt());		// ID chacra		
		msj.setIPorigen(InetAddress.getByName(readString(in))); // IP origen
		msj.setCuerpo(readString(in));
		
		return msj;
		
	}
	
	// Permite separar mensajes. Inserto primero la long del mensaje 
	// (Framing por longitud de datos)
	public void enmarcar(byte[] msj, DataOutputStream out) throws IOException{
		out.writeInt(msj.length);
		out.write(msj);
	}

	public byte[] desenmarcar(DataInputStream in) throws IOException{
		int len = in.readInt();

		byte[] buf = new byte[len];
		in.readFully(buf);

		return buf;
	}

	
}
